#!/bin/bash

START_HOME=$(dirname $0)

START_LOGFILE=$START_HOME/logs/starter.log
PID_FILE=$START_HOME/server.pid
SERVER_PORT=9999

echo $START_HOME

function tostarthome() {
    cd $START_HOME
}

#test if port exist
function testport() {
    if netstat -an | egrep ":$1 .*LISTEN" > /dev/null
    then
        return 0
    else
        return 1
    fi
}

#test if program is running
function testrun() {
    if test -f $1
    then
        pid=`cat $1`
        if ps ax 2>/dev/null | egrep "^ *$pid.*$2" > /dev/null
        then
            return 0
        else
            rm $1
            return 1
        fi
    else
        return 1
    fi
}

case $1 in
 "start")
    if testrun $PID_FILE java
      then
	echo "minaserver server is already running!"
      else
        if testport $SERVER_PORT
	then
		echo "Another Server is already running at:$SERVER_PORT!"
	else
		tostarthome
		echo "Starting Minaserver Server..."
		nohup java -Xms512m -Xmx4096m -cp $START_HOME/serverStartup.jar ServerStartup com.doeis.minaserver.ServerStartup >> $START_LOGFILE 2>&1 &
		echo $! > $PID_FILE			
	fi
      fi
    ;;

"stop")    
	if nohup java -cp $START_HOME/serverStartup.jar ServerStartup com.doeis.minaserver.ServerShutdown >> $START_LOGFILE 2>&1
	then 
		echo "Stopping Minaserver Server..."
		sleep 2
		test -f $PID_FILE && rm -f $PID_FILE   
		echo "Minaserver Server Stopped"
	else		
		echo "Stop Minaserver Server Fail"
	fi
    ;;

"kill")
      if test -f $PID_FILE
      then
          kill `cat $PID_FILE` >> $START_LOGFILE 2>&1
          echo "Killing Minaserver Server..."
          sleep 2
          test -f $PID_FILE && rm -f $PID_FILE
      else
	echo "Minaserver Server is not running."
      fi
    ;;

    
*)
    echo "Transaction Server Usage: "
        echo "    start        Start Minaserver Server"
	echo "    stop         Stop Minaserver Server"
        echo "    kill         Kill Minaserver Server"
    ;;     
esac
